package cn.edu.hnpu.news;

import android.app.Application;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.edu.hnpu.news.utils.CrashHandler;

/**
 * @author LuLei
 * @date 2015年10月21日 上午10:25:59
 */

public class MyApplication extends Application {


	private static MyApplication mApplication;
	public String share_pic;

	public synchronized static MyApplication getInstance() {
		return mApplication;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mApplication = this;
		createDir();
		initImagePath();
		CrashHandler crashHandler = CrashHandler.getInstance(); // 捕获异常崩溃信息
		crashHandler.init(getApplicationContext());
	}

	public void createDir() {
		String log_path;
		try {
			// 得到一个路径，内容是sdcard的文件夹路径和名字
			log_path = Environment.getExternalStorageDirectory()
					.getCanonicalPath() + Constants.DLOG;
			File log = new File(log_path);
			if (!log.exists()) {
				// 若不存在，创建目录，可以在应用启动的时候创建
				log.mkdirs();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化图片路径
	 */
	private void initImagePath() {
		try {
			if (Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState())
					&& Environment.getExternalStorageDirectory().exists()) {
				share_pic = Environment.getExternalStorageDirectory()
						.getAbsolutePath() + Constants.DATA_PATH + Constants.LOGO_NAME;
			} else {
				share_pic = getFilesDir().getAbsolutePath()
						+ Constants.DATA_PATH + Constants.LOGO_NAME;
			}
			// 获得封装 文件的InputStream对象
			InputStream is = getResources().openRawResource(
					R.raw.logo);
			// 创建图片文件夹
			File file = new File(share_pic);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(share_pic);
			byte[] buffer = new byte[8192];
			int count = 0;
			// 开始复制Logo图片文件
			while ((count = is.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
			}
			fos.close();
			is.close();
		} catch (Throwable t) {
			t.printStackTrace();
			share_pic = null;
		}
	}

}
